// transfer.js - 镜像传输前端逻辑
class TransferPage {
    constructor() {
        this.currentTask = null;
        this.statusCheckInterval = null;
        this.init();
    }

    init() {
        console.log('TransferPage 初始化开始...');
        this.bindTransferForm();
        this.loadRecentImages();
        this.setupDragAndDrop();
        this.bindRestartButton();
        console.log('TransferPage 初始化完成');
    }

    bindTransferForm() {
        const form = document.getElementById('transferForm');
        if (!form) {
            console.error('找不到 transferForm 元素');
            return;
        }

        console.log('绑定传输表单事件...');
        
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            console.log('表单提交事件触发');
            
            const imageName = document.getElementById('imageName').value;
            const targetServer = document.getElementById('targetServer').value;
            const targetPath = document.getElementById('targetPath').value;

            console.log('表单数据:', { imageName, targetServer, targetPath });

            if (!imageName || !targetServer || !targetPath) {
                this.showToast('请填写所有必填字段', 'error');
                return;
            }

            try {
                console.log('发送传输请求...');
                const response = await fetch('/transfer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        image_name: imageName,
                        target_server_id: parseInt(targetServer),
                        target_path: targetPath
                    })
                });

                console.log('响应状态:', response.status);
                const data = await response.json();
                console.log('响应数据:', data);

                if (response.ok) {
                    this.showToast('传输任务已开始', 'success');
                    this.saveRecentImage(imageName);
                    this.monitorTask(data.task_id);
                } else {
                    throw new Error(data.error || '传输任务创建失败');
                }

            } catch (error) {
                console.error('Transfer error:', error);
                this.showToast(error.message, 'error');
            }
        });
        
        console.log('传输表单事件绑定完成');
    }

    async monitorTask(taskId) {
        console.log('开始监控任务:', taskId);
        this.currentTask = { id: taskId, status: 'pending' };
        
        const progressArea = document.getElementById('progressArea');
        const progressBar = document.getElementById('progressBar');
        const progressStatus = document.getElementById('progressStatus');
        const progressPercent = document.getElementById('progressPercent');
        const logOutput = document.getElementById('logOutput');
        const restartButton = document.getElementById('restartButton');

        // 显示进度区域
        progressArea.style.display = 'block';
        if (restartButton) restartButton.style.display = 'none';
        
        // 清空日志和重置进度
        if (logOutput) logOutput.innerHTML = '';
        if (progressBar) progressBar.style.width = '0%';
        if (progressPercent) progressPercent.textContent = '0%';
        if (progressStatus) progressStatus.textContent = '准备开始传输...';
        
        this.addLog('开始镜像传输流程...');

        // 轮询任务状态
        this.statusCheckInterval = setInterval(async () => {
            try {
                console.log('检查任务状态:', taskId);
                const response = await fetch(`/transfer/status/${taskId}`);
                const data = await response.json();

                if (data.success) {
                    // 更新进度和状态
                    if (progressBar) progressBar.style.width = data.progress + '%';
                    if (progressPercent) progressPercent.textContent = Math.round(data.progress) + '%';
                    if (progressStatus) progressStatus.textContent = data.message;
                    
                    // 添加日志
                    this.addLog(data.message, data.status === 'failed' ? 'error' : 'info');
                    
                    // 更新当前任务状态
                    this.currentTask = {
                        id: taskId,
                        status: data.status,
                        progress: data.progress,
                        message: data.message
                    };

                    // 任务完成或失败时停止轮询
                    if (['completed', 'failed'].includes(data.status)) {
                        clearInterval(this.statusCheckInterval);
                        if (restartButton) restartButton.style.display = 'block';
                        
                        if (data.status === 'completed') {
                            this.addLog('传输任务完成!', 'info');
                            this.showToast('镜像传输成功!', 'success');
                        } else {
                            this.addLog('传输任务失败!', 'error');
                            this.showToast('镜像传输失败', 'error');
                        }
                    }
                } else {
                    this.addLog(`状态检查失败: ${data.error}`, 'error');
                    clearInterval(this.statusCheckInterval);
                    if (restartButton) restartButton.style.display = 'block';
                }

            } catch (error) {
                console.error('状态检查错误:', error);
                this.addLog(`状态检查错误: ${error}`, 'error');
                clearInterval(this.statusCheckInterval);
                if (restartButton) restartButton.style.display = 'block';
            }
        }, 2000);
    }

    // 添加日志
    addLog(message, type = 'info') {
        const logOutput = document.getElementById('logOutput');
        if (!logOutput) return;
        
        const timestamp = new Date().toLocaleTimeString();
        const logEntry = document.createElement('div');
        logEntry.className = 'log-entry';
        
        // 根据类型设置颜色类
        const typeClass = type === 'error' ? 'log-error' : 
                         type === 'warning' ? 'log-warning' : 'log-info';
        
        logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> <span class="${typeClass}">${message}</span>`;
        logOutput.appendChild(logEntry);
        logOutput.scrollTop = logOutput.scrollHeight;
    }

    bindRestartButton() {
        const restartButton = document.getElementById('restartButton');
        if (!restartButton) return;
        
        restartButton.addEventListener('click', () => {
            const progressArea = document.getElementById('progressArea');
            const transferForm = document.getElementById('transferForm');
            
            if (progressArea) progressArea.style.display = 'none';
            if (transferForm) transferForm.reset();
            
            // 清除轮询间隔
            if (this.statusCheckInterval) {
                clearInterval(this.statusCheckInterval);
            }
        });
    }

    saveRecentImage(imageName) {
        let recentImages = JSON.parse(localStorage.getItem('recentImages') || '[]');
        recentImages = recentImages.filter(img => img !== imageName);
        recentImages.unshift(imageName);
        recentImages = recentImages.slice(0, 10); // 只保存最近10个
        localStorage.setItem('recentImages', JSON.stringify(recentImages));
    }

    loadRecentImages() {
        const recentImages = JSON.parse(localStorage.getItem('recentImages') || '[]');
        const imageInput = document.getElementById('imageName');
        
        if (recentImages.length > 0 && imageInput) {
            // 创建数据列表提供自动完成
            const datalist = document.createElement('datalist');
            datalist.id = 'recentImagesList';
            
            recentImages.forEach(image => {
                const option = document.createElement('option');
                option.value = image;
                datalist.appendChild(option);
            });
            
            document.body.appendChild(datalist);
            imageInput.setAttribute('list', 'recentImagesList');
        }
    }

    setupDragAndDrop() {
        const dropZone = document.getElementById('imageName');
        if (!dropZone) return;

        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('drag-over');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('drag-over');
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('drag-over');
            
            // 处理拖放的文件（如果有相关功能）
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                // 这里可以添加处理拖放文件的逻辑
                console.log('Dropped file:', files[0].name);
            }
        });
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'pulling': '拉取镜像',
            'saving': '保存镜像',
            'transferring': '传输中',
            'verifying': '验证中',
            'completed': '完成',
            'failed': '失败',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }

    getStatusClass(status) {
        const classMap = {
            'pending': 'bg-secondary',
            'pulling': 'bg-info',
            'saving': 'bg-warning',
            'transferring': 'bg-primary',
            'verifying': 'bg-info',
            'completed': 'bg-success',
            'failed': 'bg-danger',
            'cancelled': 'bg-secondary'
        };
        return classMap[status] || 'bg-secondary';
    }

    showToast(message, type = 'info') {
        // 检查是否有全局的toast系统
        if (window.mirrorTransferSystem && window.mirrorTransferSystem.showToast) {
            window.mirrorTransferSystem.showToast(message, type);
        } else {
            // 备用方案：使用浏览器原生 alert
            alert(`${type.toUpperCase()}: ${message}`);
        }
    }
}

// 初始化传输页面
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，初始化TransferPage...');
    if (document.getElementById('transferForm')) {
        console.log('找到transferForm，创建TransferPage实例');
        window.transferPage = new TransferPage();
    } else {
        console.error('未找到transferForm元素');
    }
});
